package com.qf.service.impl;

import com.qf.constant.CacheConstants;
import com.qf.constant.StrategyConstants;
import com.qf.feign.CacheFeign;
import com.qf.model.StandardSubmit;
import com.qf.service.FilterChainService;
import com.qf.util.PushMsgUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Set;

/*
 *@Description:限流策略
 *@author:刘哥
 *@Date:86180 2022/10/19 17:46
 */
@Service("limitFiveMinutes")
@Slf4j
public class LimitFiveMinutesServiceImpl implements FilterChainService {
    @Autowired
    private CacheFeign cacheFeign;
    @Autowired
    private PushMsgUtil pushMsgUtil;
    @Override
    public boolean strategy(StandardSubmit standardSubmit) {
        log.info("[策略模块-限流策略] 开始执行==========");
        //1.获取客户id和目标手机号，组成key
        Integer clientID = standardSubmit.getClientID();
        String destMobile = standardSubmit.getDestMobile();
        //2. 如果需要校验短信内容内容相同的问题,再给key添加个前缀,短信内容
        String key= CacheConstants.CACHE_PREFIX_SMS_LIMIT +clientID + ":" + destMobile;
        //3. 获取发送时间的毫秒值,和5分钟之前的毫秒值
        long sendTime = new Date().getTime();
        long fiveMinuteBefore=sendTime - 1000*60*5;
        //4. 调用缓存模块，查询近5分钟之内，发送过几条短信
        Set<String> value = cacheFeign.zRangeByScore(key, fiveMinuteBefore, sendTime);
        //5. 判断发送条数
        if (value != null && value.size() >=3){
            //6. 已经超过限流要求。记录日志，发送消息，return false
            log.info("[策略模块 - 限流策略] 5分钟内的限流策略执行失败。。。");
            pushMsgUtil.sendLog(standardSubmit, StrategyConstants.STRATEGY_ERROR_LIMIT);
            pushMsgUtil.pushReport(standardSubmit, StrategyConstants.STRATEGY_ERROR_LIMIT);
            return false;
        }else{
            //7. 没有超过限流要求。 记录日志，return true
            log.info("[策略模块 - 限流策略] 5分钟内的限流策略执行成功！！！");
            return true;
        }

    }
}
